package com.axend.aerosense.common.util;

import android.graphics.Bitmap;
import android.util.Base64;
import android.util.Log;

import com.axend.aerosense.common.bean.UserInfo;
import com.blankj.utilcode.util.ToastUtils;
import com.axend.aerosense.base.bean.BaseImageBean;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.network.model.HttpHeaders;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HeadIconUploadService {

    /**
     *
     * @param bitmap
     * @param upType 图片类型 0用户 1紧急联系人 2受监护人
     * @param callBack
     * @param <T>
     */
    public static <T> void upload(Bitmap bitmap, int upType, String userId, SimpleCallBack<T> callBack) {

//        Log.d("myTAG", "upload: token:" + MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.headersMap.put("token", MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN));
        httpHeaders.headersMap.put("Content-type", "application/json;charset=UTF-8");
        BaseImageBean baseImageBean = new BaseImageBean(bitmapToBase64(bitmap), upType, userId);


        EasyHttp.post(UrlApi.URL.ImageIcon.getUrl())
                .headers("token", MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN))
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(baseImageBean))
                .execute(callBack);

    }

    /*
     * bitmap转base64
     * */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /*end*/

}
